import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:Lter/style/theme.dart' as theme;
import 'package:Lter/home.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:Lter/util/toast.dart';
import 'package:flutter/services.dart';
import 'package:Lter/model/app.dart';
import 'package:package_info/package_info.dart';
import 'dart:async';
import 'dart:convert';

/**
 *注册界面
 */
class SignInPage extends StatefulWidget {
  @override
  _SignInPageState createState() => _SignInPageState();
}

class _SignInPageState extends State<SignInPage> {
  /**
   * 利用FocusNode和FocusScopeNode来控制焦点
   * 可以通过FocusNode.of(context)来获取widget树中默认的FocusScopeNode
   */
  FocusNode emailFocusNode = FocusNode();
  FocusNode passwordFocusNode = FocusNode();
  FocusScopeNode focusScopeNode = FocusScopeNode();

  GlobalKey<FormState> _SignInFormKey = GlobalKey();

  bool mFirstBuild = true;

  String mUserName = "";
  String mPasswd = "";
  bool isLoging = true;

  bool isShowPassWord = false;

  void CheckWebsocketState() {
    Timer(new Duration(seconds: 1), () {
      AppInherited app = AppContainer.of(context).app;
      if (app.mWebSocket.GetState()) {
        Toast.snack(context, "正在检查版本更新!");

        app.mWebSocket.AddHandle("app_version", (jsonMap) {
          app.mWebSocket.RemoveHandle("app_version");

          PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
            if (jsonMap["app_version"] == packageInfo.version) {
              Toast.remove_snack(context);
              setState(() {
                isLoging = false;
              });
            } else {
              showDialog<Null>(
                context: context,
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text('发现新版本：' + jsonMap["app_version"]),
                    content: SingleChildScrollView(
                      child: Text(jsonMap["tip"]),
                    ),
                    actions: <Widget>[
                      FlatButton(
                        child: Text('取消'),
                        onPressed: () async {
                          await SystemChannels.platform
                              .invokeMethod('SystemNavigator.pop');
                        },
                      ),
                      FlatButton(
                        child: Text('更新'),
                        onPressed: () {
                          _launchURL(jsonMap["apk_url"]);
                        },
                      ),
                    ],
                  );
                },
              ).then((val) {
                Toast.snack(context, val);
              });
            }
          });
        });
        app.mWebSocket.Send("app_version", app.mUser, null);
      } else {
        CheckWebsocketState();
        Toast.snack(context, "服务器连接中！");
        setState(() {
          isLoging = true;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (mFirstBuild) {
      mFirstBuild = false;
      CheckWebsocketState();
    }

    return Container(
      padding: EdgeInsets.only(top: 15),
      child: Stack(
        alignment: Alignment.center,
//        /**
//         * 注意这里要设置溢出如何处理，设置为visible的话，可以看到孩子，
//         * 设置为clip的话，若溢出会进行裁剪
//         */
//        overflow: Overflow.visible,
        children: <Widget>[
          Column(
            children: <Widget>[
              //创建表单
              buildSignInTextForm(),

              /*Padding(
                padding: const EdgeInsets.only(top: 50),
                child: Text(
                  "Forgot Password?",
                  style: TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                      decoration: TextDecoration.underline),
                ),
              ),*/

              /**
               * Or所在的一行
               */
              /*Padding(
                padding: EdgeInsets.only(top: 10),
                child: Row(
//                          mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      height: 1,
                      width: 100,
                      decoration: BoxDecoration(
                          gradient: LinearGradient(colors: [
                        Colors.white10,
                        Colors.white,
                      ])),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 15, right: 15),
                      child: Text(
                        "Or",
                        style: TextStyle(fontSize: 16, color: Colors.white),
                      ),
                    ),
                    Container(
                      height: 1,
                      width: 100,
                      decoration: BoxDecoration(
                          gradient: LinearGradient(colors: [
                        Colors.white,
                        Colors.white10,
                      ])),
                    ),
                  ],
                ),
              ),

              /**
               * 显示第三方登录的按钮
               */
              SizedBox(
                height: 10,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white,
                    ),
                    child: IconButton(
                        icon: Icon(
                          FontAwesomeIcons.facebookF,
                          color: Color(0xFF0084ff),
                        ),
                        onPressed: null),
                  ),
                  SizedBox(
                    width: 40,
                  ),
                  Container(
                    padding: EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white,
                    ),
                    child: IconButton(
                        icon: Icon(
                          FontAwesomeIcons.google,
                          color: Color(0xFF0084ff),
                        ),
                        onPressed: null),
                  ),
                ],
              )*/
            ],
          ),
          Positioned(
            child: buildSignInButton(),
            top: 170,
          )
        ],
      ),
    );
  }

  /**
   * 点击控制密码是否显示
   */
  void showPassWord() {
    setState(() {
      isShowPassWord = !isShowPassWord;
    });
  }

  /**
   * 创建登录界面的TextForm
   */
  Widget buildSignInTextForm() {
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: Colors.white),
      width: 300,
      height: 190,
      /**
       * Flutter提供了一个Form widget，它可以对输入框进行分组，
       * 然后进行一些统一操作，如输入内容校验、输入框重置以及输入内容保存。
       */
      child: Form(
        key: _SignInFormKey,
        //开启自动检验输入内容，最好还是自己手动检验，不然每次修改子孩子的TextFormField的时候，其他TextFormField也会被检验，感觉不是很好
//        autovalidate: true,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Flexible(
              child: Padding(
                padding: const EdgeInsets.only(
                    left: 25, right: 25, top: 20, bottom: 20),
                child: TextFormField(
                  //关联焦点
                  focusNode: emailFocusNode,
                  onEditingComplete: () {
                    if (focusScopeNode == null) {
                      focusScopeNode = FocusScope.of(context);
                    }
                    focusScopeNode.requestFocus(passwordFocusNode);
                  },

                  decoration: InputDecoration(
                      icon: Icon(
                        FontAwesomeIcons.user,
                        color: Colors.black,
                      ),
                      hintText: "Name",
                      border: InputBorder.none),
                  style: TextStyle(fontSize: 16, color: Colors.black),
                  //验证
                  validator: (value) {
                    if (value.isEmpty) {
                      return "Name can not be empty!";
                    }
                  },
                  onSaved: (value) {
                    mUserName = value;
                  },
                ),
              ),
            ),
            Container(
              height: 1,
              width: 250,
              color: Colors.grey[400],
            ),
            Flexible(
              child: Padding(
                padding: const EdgeInsets.only(left: 25, right: 25, top: 20),
                child: TextFormField(
                  focusNode: passwordFocusNode,
                  decoration: InputDecoration(
                      icon: Icon(
                        Icons.lock,
                        color: Colors.black,
                      ),
                      hintText: "Password",
                      border: InputBorder.none,
                      suffixIcon: IconButton(
                          icon: Icon(
                            Icons.remove_red_eye,
                            color: Colors.black,
                          ),
                          onPressed: showPassWord)),
                  //输入密码，需要用*****显示
                  obscureText: !isShowPassWord,
                  style: TextStyle(fontSize: 16, color: Colors.black),
                  validator: (value) {
                    if (value == null || value.isEmpty || value.length < 6) {
                      return "Password'length must longer than 6!";
                    }
                  },
                  onSaved: (value) {
                    mPasswd = value;
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildSignInButtonText() {
    if (isLoging) {
      return CupertinoActivityIndicator(
        radius: 15.0, //值越大加载的图形越大
      );
    } else {
      return Text(
        "LOGIN",
        style: TextStyle(fontSize: 25, color: Colors.white),
      );
    }
  }

  void CheckLogin(ok(dynamic), nook(dynamic)) {
    AppInherited app = AppContainer.of(context).app;
    app.mWebSocket.AddHandle("login", (jsonMap) {
      app.mWebSocket.RemoveHandle("login");

      if (jsonMap["state"] == 1) {
        ok(jsonMap);
      } else {
        nook(jsonMap);
      }
    });

    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      Map<String, dynamic> jsonMap = Map<String, dynamic>();
      app.mUser.username = mUserName;
      app.mUser.password = mPasswd;
      app.mWebSocket.Send("login", app.mUser, jsonMap);
    });
  }

  /**
   * 创建登录界面的按钮
   */
  Widget buildSignInButton() {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.only(left: 42, right: 42, top: 10, bottom: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(5)),
          gradient: theme.AppTheme.primaryGradient,
        ),
        child: buildSignInButtonText(),
      ),
      onTap: () async => buildSignInButtonOnTap(),
    );
  }

  void buildSignInButtonOnTap() async {
    if (isLoging) {
      return;
    }

    setState(() {
      isLoging = true;
    });

    //利用key来获取widget的状态FormState,可以用过FormState对Form的子孙FromField进行统一的操作
    //如果输入都检验通过，则进行登录操作
    if (_SignInFormKey.currentState.validate()) {
      //调用所有自孩子的save回调，保存表单内容
      _SignInFormKey.currentState.save();

      CheckLogin((jsonMap) {
        AppInherited app = AppContainer.of(context).app;
        app.mUser.username = mUserName;
        app.mUser.password = mPasswd;
        app.mUser.level = jsonMap["data"][0]["level"];
        app.mUser.regtime = jsonMap["data"][0]["reg_time"];

        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(
                builder: (context) => AppContainer(
                      app: app,
                      child: NavHomeScreen(),
                    )),
            (route) => route == null);
      }, (jsonMap) {
        Toast.snack(context, "用户名或密码错误，请重试!");
      });
    }

    setState(() {
      isLoging = false;
    });
  }

  _launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      Toast.snack(context, 'Could not launch $url');
    }
  }
}
